package br.com.classificadosonline.servlet;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import br.com.classificadosonline.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.File;

import java.util.Iterator;
import java.util.List; 

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.MultipartStream;

import java.sql.SQLException;

public class GerenciarCategoriaServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private Sistema sistema = Sistema.getInstance();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GerenciarCategoriaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		String comando = request.getParameter("comando");
		
		if (comando.equals("listar")) {
		try {
			RequestDispatcher dispatcher = request.getRequestDispatcher("old/categorias.jsp");
			dispatcher.forward(request, response);
			return;
		}
		
		catch (Exception e) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("old/categorias.jsp");
				dispatcher.forward(request, response);
				return;
		} 
		
		} else if (comando.equals("editar")){
			try{
				request.setAttribute("codigoCategoria", request.getParameter("codigoCategoria"));
				RequestDispatcher dispatcher = request.getRequestDispatcher("old/editarcategoria.jsp");
				dispatcher.forward(request, response);
				return;
			}
				catch(Exception e) {
					RequestDispatcher dispatcher = request.getRequestDispatcher("old/categorias.jsp");
					dispatcher.forward(request, response);
					return;
				}
			}
				
			else if (comando.equals("excluir")) {
				try{
				int codigo = Integer.parseInt(request.getParameter("codigoCategoria"));
				sistema.excluirCategoria(codigo);
				RequestDispatcher dispatcher = request.getRequestDispatcher("old/categorias.jsp");
				dispatcher.forward(request, response);
				return;
			}
				catch(Exception e) {
					RequestDispatcher dispatcher = request.getRequestDispatcher("old/categorias.jsp");
					dispatcher.forward(request, response);
					return;
				}
			}		else if (comando.equals("novo")) {
			try{
				RequestDispatcher dispatcher = request.getRequestDispatcher("old/cadastrarcategoria.jsp");
				dispatcher.forward(request, response);
				return;
			} 
				catch(Exception e) {
					RequestDispatcher dispatcher = request.getRequestDispatcher("old/categorias.jsp");
					dispatcher.forward(request, response);
					return;
			} 
		}
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	 if (request.getParameter("comando").equalsIgnoreCase("cadastrar")){
		/*try {
			String descricao = request.getParameter("descricao");
			String foto = request.getParameter("foto");
			
			sistema.cadastrarCategoria(descricao,foto);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/categorias.jsp");
			dispatcher.forward(request, response);
			return;
			
					}
		catch (Exception e) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("/cadastrocategoria.jsp");
			dispatcher.forward(request, response);
			return;
		}
	
			*/
			
			
			
			boolean isMultiPart = ServletFileUpload.isMultipartContent(request) || false;
            
            if(isMultiPart)
            {
                ServletFileUpload upload = null;  
                DiskFileItemFactory factory = new DiskFileItemFactory();  
                factory.setSizeThreshold(1024*1024*5);  
                //factory.setRepository(new File("PATH_PARA_SALVAR_ARQUIVOS_GRANDES"));  
                upload = new ServletFileUpload(factory);  
                List fileItems;
                    try {
                            fileItems = upload.parseRequest(request);
                            Iterator it = fileItems.iterator();
                            FileItem fitem = null;  
                        FileItem farquivo = null;  
                        String descricao = "";
                        //  String assunto = "";
                       // String data = "";
                       // String nomeArquivo = "";
                        boolean inserido = false;
                        while (it.hasNext())  
                        {  
                           fitem = (FileItem) it.next();
                           if (fitem.isFormField())  
                           {  
                              if(fitem.getFieldName().equals("descricao"))  
                              {  
                                descricao = fitem.getString();
                              }
                             /* else if(fitem.getFieldName().equals("dataAtual")){
                                      data = Sistema.retornaDataSql(fitem.getString().split(" "));
                              }*/
                           }  
                           else  
                           {  
                                    //Pegando o arquivo e copiando na pasta
                                    
                              File arquivo = new File(getServletContext().getRealPath("/") + "/Arquivos/" + fitem.getName());
                                            System.out.println(arquivo.getAbsolutePath());           
                       FileOutputStream output = new FileOutputStream(arquivo);

                       InputStream is = fitem.getInputStream();

                       byte[] buffer = new byte[(int) fitem.getSize()];

                       int nLidos;

                       while ((nLidos = is.read(buffer)) >= 0)
                           output.write(buffer, 0, nLidos);
                       
                       output.flush();
                       output.close();
                              // inserido = new MaterialEstudoDAO().inserirArquivoPasta("/MaterialDownload/" + fitem.getName(), ((DisciplinaProfessor)session.getAttribute("discProf")).getIdDisciplinaProf(), assunto, data);
                       		  sistema.cadastrarCategoria(descricao,"/Arquivos/" + fitem.getName());
                           }
                        }
                        
                       // if(inserido){
                        RequestDispatcher dispatcher = request.getRequestDispatcher("/categorias.jsp");
                        dispatcher.forward(request, response);
                        return;
                      //  }
                        
                    } catch (FileUploadException e) {
                            e.printStackTrace();
                    }
            }	
	 }				
	 else
	 
	 if (request.getParameter("comando").equalsIgnoreCase("editar")){
			try {
				int cod = Integer.parseInt(request.getParameter("codigoCategoria"));
				String descricao = request.getParameter("descricao");
				String foto = request.getParameter("foto");
				sistema.modificarCategoria(cod,descricao,foto);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/categorias.jsp");
				dispatcher.forward(request, response);
				return;
			}
			catch (Exception e) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/categorias.jsp");
				dispatcher.forward(request, response);
				return;
			}
	  }/*  else
	
	 if (request.getParameter("comando").equalsIgnoreCase("excluir")){
			try {
				String descricao = request.getParameter("descricao");
				String foto = request.getParameter("foto");
				sistema.cadastrarCategoria(descricao,foto);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/categorias.jsp");
				dispatcher.forward(request, response);
				return;
			}
			catch (Exception e) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/categorias.jsp");
				dispatcher.forward(request, response);
				return;
			}
	 } */
	
	 
	}

	
}
